package com.miracle.handler.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.miracle.auth.MyUserDetail;
import com.miracle.common.response.Result;
import com.miracle.common.response.ResultInfo;
import com.miracle.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jie.xi
 * @date 2022年05月19日 15:59
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登陆成功");
        ObjectMapper objectMapper = new ObjectMapper();
        Object principal = authentication.getPrincipal();
        List<String> roles = new ArrayList<>();
        if(principal instanceof UserDetails){
            MyUserDetail userDetails = (MyUserDetail) principal;
            User user = userDetails.getUser();
            for (GrantedAuthority role : userDetails.getAuthorities()){
                roles.add(role.getAuthority());
            }
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(
                    Result.success().codeAndMessage(ResultInfo.LOGIN_SUCCESS)
                            .data("user",user)
                            .data("roles",roles)
            ));

        }
    }
}
